package cn.dglydrpy.study.mybatis.utils;

import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/**
 * @Description:  
 * @author:LY_飘涯
 * @date:2021-7-3 17:11:41 
 * @version:1.0
 */
public class SqlSessionUtils {
	
	public static SqlSession getSqlSession(boolean autoCommit){
		SqlSession sqlSession = null;
		try {
			//1.Resources工具类，配置文件的加载，把配置文件加载成字节输入流
			InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
			//2.解析了配置文件，并创建了sqlSessionFactory工厂
			SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
			//3.生产sqlSession
			if (autoCommit) {
				//事务自动提交
				sqlSession = sqlSessionFactory.openSession(true);
			}else {
				// 默认开启一个事务，但是该事务不会自动提交
                // 在进行增删改操作时，要手动提交事务
				sqlSession = sqlSessionFactory.openSession();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return sqlSession;
	}
	
	public static SqlSession getSqlSession(){
		return getSqlSession(false);
	}

}
